# encoding: utf-8

class Utility::BasicTweet
  include Mongoid::Document

  field :username, :type => String, :default => "13556731190"
  field :password, :type => String, :default => "oopsdata@2013"
  field :uid, :type => String
  field :status, :type => Hash, :default =>{
    "create_comment"  => true,
    "login" => true,
    "access" => true
  }
  field :last_use, :type => Integer, :default => Time.now.to_i
  field :api_used, :type =>  Hash, :default =>{
    "create_comment"  => 0
  }
  field :access_token, :type => String
  field :ip, :type => String
  field :expires_in, :type => Time, :default => Time.now

  field :access_time, :type => Time, :default => ->{Time.now - Oauth2::WEIBO_EXPIRE_TIME.days}

  scope :active, ->(api_name = nil) { where("status.login" => true).where("status.#{(api_name || 'access').to_s}" => true) }

  ERROR_RESCUE = {
    :retry => 1,
    :another_retry => 2,
    :im_sorry => 3,
    :oops =>0
  }

  # # # # # # # # # # # # # # # #
  #
  # 从这里开始是类方法
  #
  # # # # # # # # # # # # # # # #

  def self.get_spammer(api_name = nil)
    result = Utility::Result.new
    if api_name
      spammers = self.active.where("status.#{api_name.to_s}" => true)
    else
      spammers = self.active
    end
    if spammers.empty?
      logger.info ">遇到错误: 没有可用僵尸号了"
      result.error = 20003
      result.error = "User does not exists"
      result.request = api_name
      return result
    else
      logger.info ">获取账号: 总计#{spammers.count}个账号"
      spammer = spammers[rand(spammers.count)]
      if block_given?
        error_count = 0
        while((error_count += 1) <= 3)
          error, result = yield(spammer)
          case error
          when ERROR_RESCUE[:retry]
            logger.info ">处理错误: 重新请求第#{error_count}次"
          when ERROR_RESCUE[:another_retry]
            #Optimize 临时解决方案
            logger.info ">处理错误: 切换账号,重新请求第#{error_count}次"
            spammers = Utility::Weibo.active.where("status.#{api_name.to_s}" => true)
            if spammers.empty?
              logger.info ">遇到错误: 没有可用僵尸号了"
              result.error = 20003
              result.msg[:content] = "User does not exists"
              result.request = api_name
              return result
            else
              spammer = spammers[rand(spammers.count)]
              logger.info ">处理错误: 切换账号,当前账号为#{spammer.username}"
            end
          when ERROR_RESCUE[:im_sorry]
            logger.info ">处理错误: 发生了奇奇怪怪的错误,暂时处理不能"
            return result
          when false
            return result
          else
            return result
          end
        end
        return result
      else
        return spammer
      end
    end
  end

  def self.search(keyword, options = {})
    logger.info ">准备登陆: 开始获取账号"
    if worker = self.active[rand(self.active.count)]
      worker.search(keyword, options)
    else
      logger.info ">登录失败: 没有可用账号了"
      false
    end
  end

  def self.destroy_comment_batch(tweets)
    dtweets = {}
    Statistics::Tweet.success.where(:_id.in => tweets).each do |tweet|
      if tweet.spammer_id
        dtweets[tweet.spammer_id] ||=[]
        dtweets[tweet.spammer_id] << tweet.cid if tweet.cid
      else
        tweet.destroy
      end
    end
    dtweets.each do |spammer_id, _dtws|
      if spamer = Utility::BasicTweet.where(:uid => spammer_id).first
        spamer.destroy_comment_batch(_dtws.join(','))
      end
    end
    Statistics::Tweet.where(:_id.in => tweets).destroy_all
  end

  # # # # # # # # # # # # # # # #
  #
  # 从这里开始是对外开放的接口
  #
  # # # # # # # # # # # # # # # #

  def http_client
    @http_client ||= Mechanize.new do |agent|
      agent.user_agent_alias                    = 'Mac Safari'
      agent.request_headers["X-Forwarded-For"]  = self.ip || "114.246.166.166"
      agent.request_headers["CLIENT-IP"]        = self.ip || "114.246.166.133"
      # agent.request_headers["HTTP_X_FORWARDED_FOR"] = "123.118.115.9"
    end
  end


end
